#pragma once
#ifndef _COMM_HPP_
#define _COMM_HPP_

#include <iostream>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <sys/ipc.h>
#include <sys/shm.h>

#define PATHNAME "."
#define PROJ_ID 0x66
#define MAX_SIZE 4096


key_t getKey()
{
    key_t key = ftok(PATHNAME, PROJ_ID);
    if (key < 0)
    {
        perror("getKey");
        exit(1);
    }
    return key;
}

int getShmHelper(key_t k, int flags)
{
    int shmid = shmget(k, MAX_SIZE, flags);
    if (shmid < 0)
    {
        perror("getShmHelper");
        exit(2);
    }
    return shmid;
}

int createShm(key_t k)
{
    return getShmHelper(k, IPC_CREAT | IPC_EXCL | 0600);
}

int getShm(key_t k)
{
    return getShmHelper(k, IPC_CREAT);
}



void* attachShm(int shmid)
{
    void* mem = shmat(shmid, nullptr, 0);
    if ((long long)mem == -1L)
    {
        perror("attachShm");
        exit(3);
    }
    return mem;
}

void detachShm(void* start)
{
    if (shmdt(start) == -1)
    {
        perror("detachShm");
    }
}

void delShm(int shmid)
{
    if (shmctl(shmid, IPC_RMID, nullptr) == -1)
    {
        perror("delShm");
    }
}

#endif